﻿namespace LeadMaster.Controllers
{
  using System;
  using System.Linq;
  using System.Web.Mvc;
  using LeadMaster.DAL;
  using LeadMaster.ViewModels;
  using System.Web.Security;
  using LeadMaster.Helpers;
  using System.Collections.Generic;
  using LeadMaster.Models;
  using System.Data;
  using LeadMaster.Properties;
  using System.Configuration;
  using System.Data.Entity;
  using System.Data.Entity.Core.Objects;
  using PagedList;

    public class FinancialController : Controller
    {

      private DunsmoreContext db = new DunsmoreContext();
        
      public ActionResult Index()
        {
          ViewModelFinancials viewModel = new ViewModelFinancials();
          ViewBag.FinanceTypesID = new SelectList(db.FinanceTypes, "FinanceTypesID", "Description");
          viewModel.FilterStart = DateTime.Now;
          viewModel.FilterEnd = DateTime.Now;
          return View(viewModel);
        }

      [HttpPost]
      public ActionResult Index(ViewModelFinancials viewModel)
      {
        viewModel.FilterEnd=viewModel.FilterEnd.AddDays(1).AddMinutes(-1);
        viewModel.ListEarnt = db.Earnt
               .Join(db.FinanceActions, a => a.EarntID, b => b.EarntID, (a, b) => new { a, b })
               .Where(w => w.a.DateUpdated >= viewModel.FilterStart && w.a.DateUpdated <= viewModel.FilterEnd)
               .Where(w => w.b.FinanceTypesID == viewModel.FinanceTypesID)
               .OrderByDescending(m => m.a.LeadStatus.LeadFlag.DisplayOrder)
               .Select(m => new EarntWithFinanceType { Earnt= m.a, FinanceType = m.b.FinanceType.Description })
               .ToList();
        ViewBag.FinanceActionFilter = db.FinanceTypes.Find(viewModel.FinanceTypesID).Description;

        return View("FilteredList", viewModel);
      }

      public ActionResult Edit(int id)
      {
        ViewModelFinancials viewModel = new ViewModelFinancials();
        viewModel.Earnt = db.Earnt.Find(id);
        viewModel.FinanceActions = db.FinanceActions.Where(m => m.EarntID == id).FirstOrDefault();
        ViewBag.FinanceTypesID = new SelectList(db.FinanceTypes, "FinanceTypesID", "Description", viewModel.FinanceActions.FinanceTypesID);
        viewModel.LeadStatus = db.LeadStatus.Find(viewModel.Earnt.LeadStatusID);
        viewModel.ListLeadResults = db.LeadResults.Where(m => m.BlockId == viewModel.LeadStatus.BlockID).ToList();
        return View(viewModel);
      }

      [HttpPost]
      public void Edit(ViewModelFinancials viewModel)
      {
        viewModel.FinanceActions.FinanceTypesID = viewModel.FinanceTypesID;
        viewModel.FinanceActions.DateOfAction = DateTime.Now;
        db.Entry(viewModel.FinanceActions).State = EntityState.Modified;
        db.SaveChanges();
      }

    }
}
